package com.gpoint.rdp.card.department.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;


import com.gpoint.rdp.card.department.persistence.entity.DepartmentPo;
import com.gpoint.rdp.card.department.service.DepartmentQueryService;
import com.gpoint.rdp.card.department.service.DepartmentService;
import com.gpoint.rdp.common.DoorConfig;
import com.gpoint.rdp.common.enums.DepartmentEnum;

import cn.pluss.platform.service.AuthRemoteService;

import com.gpoint.rdp.base.core.entity.ResultMessage;
import com.gpoint.rdp.base.core.exception.BaseException;
import com.gpoint.rdp.base.core.util.AppUtil;
import com.gpoint.rdp.base.core.util.BeanUtils;
import com.gpoint.rdp.base.core.util.string.StringUtil;
import com.gpoint.rdp.base.web.controller.GenericController;
import com.gpoint.rdp.base.web.util.RequestUtil;

/**
 * 
 * @author Administrator
 *
 */

@Controller
@RequestMapping("/rdp/card/department/department/")
public class DepartmentController extends GenericController {

    @Resource
    private DepartmentService departmentService;

    @Resource
    private DepartmentQueryService departmentQueryService;
    
    //private String servicecode="8342";
    
    private DoorConfig config=AppUtil.getBean(DoorConfig.class);
    String servicecode=config.getServicecode();

    /*
     * @RequestMapping("tree") public ModelAndView tree(HttpServletRequest request, HttpServletResponse response) throws
     * Exception { String preUrl = RequestUtil.getPrePage(request); User sysUser = currentContext.getCurrentUser();
     * String userId = sysUser.getUserId(); // 用户id List < PartyAttrValuePo > urList = new ArrayList < PartyAttrValuePo
     * >(); String value = null; if (StringUtil.isNotEmpty(userId)) { String zzbmId =
     * partyAttrRepository.getByAttrKey("zzbm").getId(); // 组织编码 String whereSql = " PARTY_ID_=" + "\'" + userId + "\'"
     * + " AND ATTR_ID_ =" + "\'" + zzbmId + "\'"; DefaultQueryFilter paramQueryFilter = new DefaultQueryFilter();
     * paramQueryFilter.addParamsFilter("whereSql", whereSql); urList =
     * partyAttrValueRepository.query(paramQueryFilter); if (urList.size() != 0) { value = urList.get(0).getValue(); } }
     * if (StringUtil.isEmpty(value)) { return new ModelAndView("error/errorServiceCode.jsp"); } else { return
     * getAutoView().addObject("returnUrl", preUrl).addObject("zzbm", value); } }
     */

    
    
	@RequestMapping("tree")
	 public ModelAndView list(HttpServletRequest request,HttpServletResponse response) throws Exception{
		  ModelAndView mv=getAutoView();
		  return mv;	  
	 }
    /**
     * 获取结构数据
     */    
    @RequestMapping("getTreeData")
    @ResponseBody
    public List < DepartmentPo > getTreeData(HttpServletRequest request, HttpServletResponse reponse) throws Exception {
        List < DepartmentPo > departmentList = departmentQueryService.query(servicecode, null, null);//
        if (BeanUtils.isEmpty(departmentList))
            departmentList = new ArrayList < DepartmentPo >();
        /* 构建根节点 */
        DepartmentPo department = new DepartmentPo();
        department.setOrgcode("0");
        department.setOrgname("校园组织结构树");
        departmentList.add(0, department);
        return departmentList;
    }

    /**
     * 编辑信息页面
     */
    @RequestMapping("edit")
    public ModelAndView edit(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String preUrl = RequestUtil.getPrePage(request);
        String id = RequestUtil.getString(request, "id");
        String parentcode = RequestUtil.getString(request, "parentcode");
        String parentFullName = "";
        DepartmentPo po = null;
        if (StringUtil.isNotEmpty(id)) {
            po = departmentQueryService.getById(id);
            parentFullName = getNodeFullName(po.getServicecode(),po.getParentcode());
            po.setParentFullName(parentFullName);
        }
        else {
            po = new DepartmentPo();
            po.setParentcode(parentcode);
            parentFullName = getNodeFullName(servicecode,parentcode);
            po.setParentFullName(parentFullName);
        }
        DepartmentEnum[] typeEnums = DepartmentEnum.values();
        
        ModelAndView mv = getAutoView();        
        mv.addObject("typeEnums", typeEnums);        
        mv.addObject("department", po).addObject("returnUrl", preUrl);
        return mv;
    }

    @RequestMapping("importList")
    public ModelAndView importList(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String preUrl = RequestUtil.getPrePage(request);
        return getAutoView().addObject("returnUrl", preUrl);
    }

    /**
     * 明细页面
     */
    @RequestMapping("get")
    public ModelAndView get(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String preUrl = RequestUtil.getPrePage(request);
        String id = RequestUtil.getString(request, "id");
        DepartmentPo department = null;
        if (StringUtil.isNotEmpty(id)) {
        	department = departmentQueryService.getById(id);
        }  
        Map<String,String> typeMap = DepartmentEnum.getTypeMap();
        
        ModelAndView mv=getAutoView();
        return mv.addObject("department", department).addObject("typeMap", typeMap).addObject("returnUrl", preUrl);
    }

    /**
     * 保存信息
     */
    @RequestMapping("save")
    public void save(HttpServletRequest request, HttpServletResponse response) throws Exception {
        ResultMessage message = null;
        try {
            String json = RequestUtil.getString(request, "json");
            if (StringUtil.isEmpty(json))
                throw new BaseException("json缺失");

            DepartmentPo po = DepartmentPo.fromJsonString(json);
            if (BeanUtils.isEmpty(po))
                throw new BaseException("po序列化失败");
            if (StringUtil.isEmpty(po.getOrgname()))
                throw new BaseException("参数缺失/错误");

            // 新增
            if (StringUtil.isEmpty(po.getId())) {
                int seq = departmentQueryService.getSeq();
                if ("0".equals(po.getParentcode()))
                    po.setParentcode("");
                if (StringUtil.isEmpty(po.getOrgcode()))
                    po.setOrgcode(String.valueOf(seq));
                po.setId(String.valueOf(seq));
                po.setCreatetime(new Date());
                //po.setCreateuser(getSysUser().getUserId());
                po.setServicecode(servicecode);//,MyConfig.SERVICE_CODE)
                departmentService.save(po);
            }
            // 编辑
            else {
                DepartmentPo podb = departmentQueryService.getById(po.getId());
                if (BeanUtils.isEmpty(podb)) {
                	throw new BaseException("非系统数据");
                }                   
                Map < String, Object > map = new HashMap < String, Object >(256);
                if (!po.getOrgcode().equals(podb.getOrgcode()))
                    map.put("ORGCODE", po.getOrgcode());
                if (!po.getOrgname().equals(podb.getOrgname()))
                    map.put("ORGNAME", po.getOrgname());
                if (!po.getTypecode().equals(podb.getTypecode()))
                    map.put("TYPECODE", po.getTypecode());
                if (!po.getFlag().equals(podb.getFlag()))
                    map.put("FLAG", po.getFlag());
                if (!po.getRemark().equals(podb.getRemark()))
                    map.put("REMARK", po.getRemark());
                if (!po.getParentcode().equals(podb.getParentcode()))
                    map.put("PARENTCODE", po.getParentcode());
                if (map.size() > 0) {
                    map.put("CREATETIME", new Date());

                    // 更新子节点parentcode
                    if (map.containsKey("ORGCODE")) {
                    	 departmentService.updateParentCode(podb.getServicecode(), podb.getOrgcode(), po.getOrgcode());
                    }                       
                    // 更新
                    departmentService.updateMapByIds(new String[] { podb.getId() }, map);
                }
            }
            message = new ResultMessage(ResultMessage.SUCCESS, "保存成功");
        }
        catch (Exception e) {
            message = new ResultMessage(ResultMessage.FAIL, "保存失败," + e.getMessage());
            logger.error("保存失败，" + e.getMessage(), e);
        }
        writeResultMessage(response.getWriter(), message);
    }

    /**
     * 批量删除【】记录
     */
    @RequestMapping("remove")
    public void remove(HttpServletRequest request, HttpServletResponse response) throws Exception {
        ResultMessage message = null;
        try {
            String id = RequestUtil.getString(request, "id");
            if (StringUtil.isEmpty(id))
                throw new BaseException("参数缺失/错误");
            departmentService.deleteById(id);
            //MyConfig.initDepartment();
            message = new ResultMessage(ResultMessage.SUCCESS, "删除成功");
        }
        catch (Exception e) {
            message = new ResultMessage(ResultMessage.FAIL, "删除失败，" + e.getMessage());
            logger.error("删除失败，" + e.getMessage(), e);
        }
        writeResultMessage(response.getWriter(), message);
    }

    /**
     * 下载
     */
//    @RequestMapping("downLoad")
//    public ResponseEntity < byte[] > downLoad(HttpServletResponse resp, HttpServletRequest req) throws Exception {
//        File file = ResourceUtils.getFile(
//                JasperReportUtil.class.getClassLoader().getResource("/").getPath() + "excelTemplate/班级导入模板.xls");
//        return ResponseUtils.buildResponseEntity(file);
//    }

//    @RequestMapping("upload")
//    @ResponseBody
//    public Map < String, String > upload(HttpServletRequest request, HttpServletResponse response) throws Exception {
//        HashMap < String, String > map = new HashMap < String, String >();
//        try {
//            String zzbm = RequestUtil.getString(request, "zzbm");
//            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
//            MultipartFile fj = multipartRequest.getFile("file");
//            File f = File.createTempFile("tmp", null);
//            fj.transferTo(f);
//            f.deleteOnExit();
//            Map < String, List < List < String > > > m = ExcelUtil.readOrgXls(f);
//            List < List < String > > list = m.get("orgList");
//            departmentService.addOrgByList(list, zzbm, null);
//            map.put("message", "导入成功!");
//        }
//        catch (Exception e) {
//            e.printStackTrace();
//            map.put("message", "导入失败!" + e.getMessage());
//        }
//        return map;
//    }

    @RequestMapping("listAll")
    @ResponseBody
    public List < DepartmentPo > listAll(HttpServletRequest request, HttpServletResponse reponse) throws Exception {
        String typecode = RequestUtil.getString(request, "typecode");
        List < DepartmentPo > departmentList = departmentQueryService.queryByTypeCode(servicecode, typecode);
        return departmentList;
    }

    @RequestMapping("list_json_tree")
    @ResponseBody
    public List < Map < String, Object > > listJsonByServiceCode(HttpServletRequest request,
            HttpServletResponse reponse) throws Exception {
        try {
            String typecode = RequestUtil.getString(request, "typecode");
            List < DepartmentPo > list = departmentQueryService.query(servicecode, null, typecode);//MyConfig.SERVICE_CODE,
            if (!BeanUtils.isEmpty(list)) {
                List < Map < String, Object > > listMap = new ArrayList < Map < String, Object > >();
                for (DepartmentPo po : list) {
                    Map < String, Object > map = new HashMap < String, Object >(256);
                    map.put("typecode", po.getTypecode());
                    map.put("parentId", po.getParentcode());
                    map.put("id", po.getOrgcode());
                    map.put("name", po.getOrgname());
                    map.put("flag", po.getFlag());
                    map.put("key", po.getOrgcode());
                    listMap.add(map);
                }
                return listMap;
            }
            return null;
        }
        catch (Exception e) {
            return null;
        }
    }
    
    private String getNodeFullName(String serviceCode,String orgCode) {
		String name = "";
		while (StringUtils.isNotEmpty(orgCode)&&StringUtils.isNotEmpty(serviceCode) && !"0".equals(orgCode)) {
			DepartmentPo po = departmentQueryService.getByOrgcode(serviceCode, orgCode);

			if (BeanUtils.isNotEmpty(po)) {
				orgCode = po.getParentcode();
				name = StringUtils.isEmpty(name)?po.getOrgname(): po.getOrgname() + "/" + name;
			} else {
				orgCode = "";
			}
		}
		return name;
	}
}